package demoMod.moduploader.utils;

import com.badlogic.gdx.Gdx;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Preferences implements Serializable {
    private static final Logger log = LogManager.getLogger(Preferences.class);

    private int[] resolution;
    private String language = "zhs";
    private String lastOpenPath;

    private static Preferences inst;
    private static final Gson gson = new Gson();

    public static Preferences getPreferences() {
        if (inst == null) {
            inst = new Preferences();
        }
        return inst;
    }

    public int[] getResolution() {
        return resolution;
    }

    public void setResolution(int[] resolution) {
        this.resolution = resolution;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getLastOpenPath() {
        return lastOpenPath;
    }

    public void setLastOpenPath(String lastOpenPath) {
        this.lastOpenPath = lastOpenPath;
    }

    public static void save() {
        File file = new File("mod-uploader-config.json");
        if (!file.exists()) {
            try {
                file.createNewFile();
                log.info("Successfully created config file.");
            } catch (IOException e) {
                log.error("Exception occurred while saving preferences!", e);
            }
        }
        try {
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            writer.write(gson.toJson(inst));
            writer.flush();
            writer.close();
            log.info("Successfully saved preferences.");
        } catch (IOException e) {
            log.error("Exception occurred while saving preferences!", e);
        }
    }

    public static void load() {
        File file = new File("mod-uploader-config.json");
        if (file.exists()) {
            inst = gson.fromJson(Gdx.files.absolute(file.getAbsolutePath()).readString("UTF-8"), new TypeToken<Preferences>(){}.getType());
        }
    }

    public static Gson getGson() {
        return gson;
    }
}
